package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.Comment;
import cn.huhst.cas.weisiqian.service.CommentService;
import cn.huhst.cas.weisiqian.util.JSON;

@WebServlet("/AddComment.do")
public class AddComment extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(AddComment.class);
	private CommentService commentservice = null;

	public AddComment() {
		super();
		commentservice = new CommentService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String strparentid = request.getParameter("parentid");
		String strcommenttype = request.getParameter("commenttype");
		String strcontent = request.getParameter("content");
		String strauthor = (String) request.getSession().getAttribute("username");

		JSON json = new JSON();
		json = Comment.checkParentid(strparentid, json);
		json = Comment.checkCommenttype(strcommenttype, json);
		json = Comment.checkContent(strcontent, json);
		json = Comment.checkAuthor(strauthor, json);

		if (json.isEmpty()) {
			int parentid = Integer.parseInt(strparentid);
			int commenttype = Integer.parseInt(strcommenttype);
			Comment comment = new Comment();
			comment.setParentid(parentid);
			comment.setCommenttype(commenttype);
			comment.setContent(strcontent);
			comment.setAuthor(strauthor);
			comment.setWritetime(new java.sql.Date(new java.util.Date().getTime()));
			comment.setLikecount(0);
			comment.setDislikecount(0);
			boolean result = commentservice.addComment(comment);
			if (result) {
				json.putOKMSG("评论成功");
				logger.info("评论成功");
			} else {
				json.putErrorMSG("评论失败");
				logger.error("评论失败");
			}
		} else {
			json.putErrorMSG("格式不符合要求");
			logger.error("格式不符合要求");
		}

		logger.error("json:" + json);
		response.setContentType("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
